<?php
// 新浪体育大厅
class IndexAction extends Action { 
	 private function urlsafe_b64decode($string) {
	    $data = base64_encode($string);
		$data = str_replace(array('+','/','='),array('-','_',''),$data);
		return $data;
	 }
	 public function players(){
		 $P = M("KxdrPlayers");
		 $pl = $P->getField("`chinese_name`,`team_flag`");
		 echo $P->getDbError();
		 foreach($pl as $k=>$p){
			 echo $k."<img src='".$p."@80h_80w.jpg' /><br />";
		 }
	 }
	public function water_mark(){
		// echo "http://kxdr.image.alimmdn.com/kxdr/image_d1450150376@watermark=1&object=".($this->urlsafe_b64decode("kxdr/image_d1450149111@100w_100h_90Q.jpg"))."&t=90&p=9&x=10&y=10";
		 $title = "中国队 VS 美国队";
		 $off2 = (int)((14-(strlen($title)-4)/3)*20);
		 echo $off2;
		$str = "http://kxdr.image.alimmdn.com/image_d1450150573";
		$str.= "@watermark=1&object=".$this->urlsafe_b64decode("kxdr/image_d1450171311"."@100w_100h.jpg")
			   ."&size=20&s=10&order=0&align=1&interval=50&t=90&p=9&x=120&y=110";
		$str.= "|watermark=1&object=".$this->urlsafe_b64decode("kxdr/image_d1450171310"."@100w_100h.jpg")
			   ."&size=20&s=10&order=0&align=1&interval=50&t=90&p=9&x=420&y=110";
		$str.= "|watermark=2&text=".$this->urlsafe_b64decode("意利")
		      ."&color=".$this->urlsafe_b64decode("#FFFFFF")
			  ."&size=50&s=20&t=90&p=9&x=265&y=240"; //4个汉字 x=215  3个汉字 215+25 2个汉字 215+50
		$str.= "|watermark=2&text=".$this->urlsafe_b64decode($title)
		      ."&color=".$this->urlsafe_b64decode("#FFFFFF")
			  ."&size=40&s=20&t=90&p=9&x=".$off2."&y=30"; //每个汉字40，两个队名最多14个汉字到头 字符串长度46 x=0
		echo "<img src='".$str."' width=\"315\" height=\"180\"/>";
		echo strlen("热那热那亚热那亚 VS 亚历山德里亚");
		return $str;
	}
	
	public function send_data_to_tae($data){
		// $url = "http://platform.sina.com.cn/sports_other/livecast_dateschedule?app_key=3633771828&date=".date("Y-m-d",time()+3600*24); //比赛日程最多支持半年
		// $data = $this->curls($url);
		// $data = json_decode($data,true);
		foreach($data["result"]["data"] as $k=>$v){
			foreach($v as $j=>$i){
				$v[$j]=urlencode($i);
			}
			$data["result"]["data"][$k]=$v;
		}
		$data = base64_encode(json_encode($data));
		// $local = "http://localhost:8080/?m=Service";
		
		$local = "http://daren.play.admin.jaeapp.com/?m=Service";
		$header = array("Host:daren.play.admin.jaeapp.com",
		  "Content-Type:application/x-www-form-urlencoded",
		  'Referer:http://daren-1.play.admin.jaeapp.com/?m=Service',
		  'User-Agent: Mozilla/4.0 (compatible; MSIE .0; Windows NT 6.1; Trident/4.0; SLCC2;)');

		$data = 'tools_id=1&env=gamma&data='.$data;
		echo $this->curl_post($header,$data,$local);
	}
	private function curl_post($header,$data,$url)
	{
		$ch = curl_init();
		$res= curl_setopt ($ch, CURLOPT_URL,$url);
		var_dump($res);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt ($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
		$result = curl_exec ($ch);
		curl_close($ch);
		if ($result == NULL) {
			return 0;
		}
		return $result;
	}
	private function curls($url, $timeout = '10')  
	{  
		// 1. 初始化  
		$ch = curl_init();  
		// 2. 设置选项，包括URL  
		curl_setopt($ch, CURLOPT_URL, $url);  
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);  
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
		curl_setopt($ch, CURLOPT_HEADER, 0);  
		// 3. 执行并获取HTML文档内容  
		$info = curl_exec($ch);  
		// 4. 释放curl句柄  
		curl_close($ch);  
		return $info;  
	}  

	private function upload_img($pic_path,$name=""){
		// 通过post到TAE的图片服务上传 
		$data = array(
            'upfile'=>'@'.($pic_path).";type=".$type.";filename=autoup_".$name.time()
        );
		$local = "http://daren.play.admin.jaeapp.com/services/img/upload.php";
		$re = json_decode($this->curl_post($header,$data,$local),true);
		$re["url"]=$re["img"]["url"];
		return $re;
	}
	private function upload_img_by_api($pic_path){
		// 通过api上传图片，必须不断刷新sessionkey
		Vendor('taobaosdk.lotusphp_runtime.Logger.Logger');
		Vendor("taobaosdk.top.RequestCheckUtil");
		Vendor("taobaosdk.top.TopClient");
		Vendor("taobaosdk.top.request.PictureUploadRequest");
		$appkey = "23270526";
		$secret = "2f6362bc86c018183805de254d589dcf";
		
		$c = new TopClient;
		$c->appkey = $appkey;
		$c->secretKey = $secret;
		$req = new PictureUploadRequest;
		$req->setPictureCategoryId(105551155449729022);
		//附件上传的机制参见PHP CURL文档，在文件路径前加@符号即可
		$req->setImg("@".$pic_path);
		$req->setImageInputTitle("Test.jpg");
		$req->setTitle("ChouJiang TuPian BuYao ShanChu"); 
		$resp = $c->execute($req, "6100916ae73d52de6443710c1a3b337d7de47da68541b0e27390555");
		if($resp->code&&$resp->msg){
			$data["status"]=0;
			$data["message"]=$resp->msg.$resp->sub_msg;
			$data["resp"]=$resp;
		}else{
			$data["status"]=1;
			$data["type"]="ajax";
			$data["name"]="@_FILES['userfile']";
			$data["url"]=(string)$resp->picture->picture_path;
		}	
		return $data;
	}
	public function img($home_flag,$guest_flag,$len,$vs,$platform){

	//引入图片处理库
	import('ORG.Util.Image.ThinkImage'); 
	//使用GD库来处理1.gif图片
	$img = new ThinkImage(THINKIMAGE_GD, '/data/home/website24/service/'.$platform); 
	$img->water($home_flag, array(100,120))
	    ->water($guest_flag, array(450,120))
	    ->text($len,"/data/home/website24/service/wqyzh.ttf",25,"#FFFFFF", THINKIMAGE_WATER_NORTH,array(0,50))
	    ->text($vs,"/data/home/website24/service/wqyzh.ttf",25,"#FFFFFF", THINKIMAGE_WATER_NORTH,array(0,230))
		->save("/data/home/website24/service/water.jpg");
	unlink($home_flag);	
	unlink($guest_flag);
	return $this->upload_img("/data/home/website24/service/water.jpg",$vs);
	}
	private function str_stat($html){
		$arr[");"]="";
		$arr["score_live_stats("]="";
		$arr["ms"]='"ms"';
		$arr["id:"]='"id":';
		$arr[",st:"]=',"st":';
		$arr["img"]='"img"';
		$arr[",n:"]=',"n":';
		$arr[",ln"]=',"ln"';
		$arr["s1"]='"s1"';
		$arr["s2"]='"s2"';
		$arr["r1"]='"r1"';
		$arr["r2"]='"r2"';
		$arr["n1"]='"n1"';
		$arr["n2"]='"n2"';
		$arr["url"]='"url"';
		$arr['{"ms":[']='[';
		$arr[']}']=']';
		$arr["'"]='"';
		
		// $arr[',"st"']='","st"';
		$arr["match_live_stats("]="";
		$arr['l"id"']='"lid"';
		$arr['type']='"type"';
		$arr['info']='"info"';
		$arr['date']='"date"';
		$arr['h"id"']='"hid"';
		$arr['a"id"']='"aid"';
		$arr['odds"id"']='"oddsid"';
		$arr['"date"2']='"date2"';
		
		foreach($arr as $k=>$a){
			$html = str_replace($k,$a,$html);
		}
		return $html;
	}
	
	public function get_football_score(){
		// 每5秒执行一次，获取最新的比赛数据
		// 实时获得全场比分、半场比分、红牌数
		Vendor('simple_html_dom');
		$html = file_get_html("http://data.sports.sina.com.cn/live/today.js"); //实时
		// $html = str_get_html("score_live_stats({ms:[{id:1171683,ln:'世俱杯',st:'完场',img:'now1.GIF',n1:'广岛三箭',n2:'奥克兰城',s1:'1-0',s2:'-',r1:'',r2:'',url:''},{id:1158554,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158553,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158542,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158541,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158530,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158529,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158518,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158493,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158494,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158505,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158506,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158517,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158643,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158614,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158613,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158602,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158601,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158590,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158589,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158578,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158577,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158566,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158565,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158644,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''}]});");
		$html = $this->str_stat($html);

		$html = iconv('gbk','utf-8',$html);//实时
		$html = (json_decode((string)$html,true));

		$Teamscore = M("KxdrGamesSoccerTeamscore");
		foreach($html as $game ){
			$save=false;
			if(S($game["id"]."st")!=$game["st"]){
				S($game["id"]."st",$game["st"]);
				$save = true;
			}
			if(S($game["id"]."s1")!=$game["s1"]){
				S($game["id"]."s1",$game["s1"]);
				$save = true;
			}
			if(S($game["id"]."r1")!=$game["r1"]){
				S($game["id"]."r1",$game["r1"]);
				$save = true;
			}
			$score = explode("-",$game["s1"]);
			$save=true;
			if($save){
				$score = explode("-",$game["s1"]);
				$data["home_team_score"]=$score[0]?$score[0]:0;
				$data["guest_team_score"]=$score[1]?$score[1]:0;
				$hafe_score = explode("-",$game["s2"]);
				$data["home_team_halfscore"]=$hafe_score[0]?$hafe_score[0]:0;
				$data["guest_team_halfscore"]=$hafe_score[1]?$hafe_score[1]:0;
				$redcard = explode("-",$game["r1"]);
				$data["home_team_redcard"]=$redcard[0]?$redcard[0]:0;
				$data["guest_team_redcard"]=$redcard[1]?$redcard[1]:0;
				$data["edit_time"]=date("Y-m-d H:i:s");
				$re = $Teamscore->where("`outside_id`=".$game["id"])->save($data);
				// echo $Teamscore->getDbError();
				if($re==false){
					$data["outside_id"]=$game["id"];
					// 实际：
					$Teamscore->where("`home_team`='".$game["n1"]."' AND `guest_team`='".$game["n2"]."' AND DATE_FORMAT(`gaming_time`,'%Y%m%d')=DATE_FORMAT(NOW(),'%Y%m%d')")->save($data);
					// $Teamscore->where("`home_team`='".$game["n1"]."' AND `guest_team`='".$game["n2"]."' AND DATE_FORMAT(`gaming_time`,'%Y%m%d')='20151210'")->save($data);
					// echo $Teamscore->_sql();
				}
			}
			if($game["st"]=="完场"){
				Vendor('simple_html_dom');
				// S($game["id"]."st",$game["st"]);
				$shuju_url = $Teamscore->where("`outside_id`=".$game["id"])->getField("shuju_url");
				preg_match("/\d+/",$shuju_url,$shuju_id);
				$url = "http://info.sports.sina.com.cn/api/live/opta_statistic.php?format=json&id=o_".$shuju_id[0];
				$da = file_get_html($url);
				$da = (json_decode((string)$da,true));
				unset($team_score);
				foreach($da["result"]["data"]["result"] as $dada){
					switch($dada["name"]){
						case "总射门":
							$team_score["home_shoot"] = $dada["l"];
							$team_score["guest_shoot"] =  $dada["r"];
						break;
						case "射正球门":
							$team_score["home_target_shoot"] = $dada["l"];
							$team_score["guest_target_shoot"] =  $dada["r"];
						break;
						case "击中门框":
							$team_score["home_woodwork_shoot"] = $dada["l"];
							$team_score["guest_woodwork_shoot"] =  $dada["r"];
						break;
						case "直塞球":
							$team_score["home_straight_plug_ball"] = $dada["l"];
							$team_score["guest_straight_plug_ball"] =  $dada["r"];
						break;
						case "越位":
							$team_score["home_offside"] = $dada["l"];
							$team_score["guest_offside"] =  $dada["r"];
						break;
						case "抢断":
							$team_score["home_steals"] = $dada["l"];
							$team_score["guest_steals"] =  $dada["r"];
						break;
						case "任意球":
							$team_score["home_free_kick"] = $dada["l"];
							$team_score["guest_free_kick"] =  $dada["r"];
						break;
						case "犯规":
							$team_score["home_foul"] = $dada["l"];
							$team_score["guest_foul"] =  $dada["r"];
						break;
						case "角球":
							$team_score["home_corner"] = $dada["l"];
							$team_score["guest_corner"] =  $dada["r"];
						break;
						case "界外球":
							$team_score["home_foul_ball"] = $dada["l"];
							$team_score["guest_foul_ball"] =  $dada["r"];
						break;
						case "超过25码长传":
							$team_score["home_over_25_yard_passes"] = $dada["l"];
							$team_score["guest_over_25_yard_passes"] =  $dada["r"];
						break;
						case "传球成功率":
							$team_score["home_pass_success_rate"] = str_replace("%","",$dada["l"]);
							$team_score["guest_pass_success_rate"] =  str_replace("%","",$dada["r"]);
						break;
						case "传中成功率":
							$team_score["home_pass_center_success_rate"] = str_replace("%","",$dada["l"]);
							$team_score["guest_pass_center_success_rate"] =  str_replace("%","",$dada["r"]);
						break;
						case "抢断成功率":
							$team_score["home_steal_success_rate"] = str_replace("%","",$dada["l"]);
							$team_score["guest_steal_success_rate"] =  str_replace("%","",$dada["r"]);
						break;
						case "头球成功率":
							$team_score["home_header_success_rate"] = str_replace("%","",$dada["l"]);
							$team_score["guest_header_success_rate"] =  str_replace("%","",$dada["r"]);
						break;
						case "控球率":
							$team_score["home_ball_control_rate"] = str_replace("%","",$dada["l"]);
							$team_score["guest_ball_control_rate"] =  str_replace("%","",$dada["r"]);
						break;
						
					}
				}
				
			}
		}
		echo 'score added.';
	}
	public function get_team_score(){
		Vendor('simple_html_dom');
		$Teamscore = M("KxdrGamesSoccerTeamscore");
		$get_game = ($Teamscore->where("DATE_FORMAT(`gaming_time`,'%Y%m%d')=DATE_FORMAT(NOW(),'%Y%m%d')")->getField("`id`,`game_id`,`shuju_url`,`home_shoot`,`home_target_shoot`,`home_woodwork_shoot`,`home_straight_plug_ball`,`home_offside`,`home_steals`,`home_free_kick`,`home_foul`,`home_corner`,`home_foul_ball`,`home_over_25_yard_passes`,`home_pass_success_rate`,`home_pass_center_success_rate`,`home_steal_success_rate`,`home_header_success_rate`,`home_ball_control_rate`,`guest_shoot`,`guest_target_shoot`,`guest_woodwork_shoot`,`guest_straight_plug_ball`,`guest_offside`,`guest_steals`,`guest_free_kick`,`guest_foul`,`guest_corner`,`guest_foul_ball`,`guest_over_25_yard_passes`,`guest_pass_success_rate`,`guest_pass_center_success_rate`,`guest_steal_success_rate`,`guest_header_success_rate`,`guest_ball_control_rate`"));
		foreach($get_game as $re){
			if($re["shuju_url"]){
			$shuju_url = $re["shuju_url"];
			$game_id = $re["id"];
			unset($re["shuju_url"]);
			unset($re["id"]);
			preg_match("/\d+/",$shuju_url,$shuju_id);
			$url = "http://info.sports.sina.com.cn/api/live/opta_statistic.php?format=json&id=o_".$shuju_id[0];
			$da = file_get_html($url);
			$da = (json_decode((string)$da,true));
			unset($team_score);
				if($da["result"]["data"]["match_info"]["status"]>=2){
					$team_score["status"] = $da["result"]["data"]["match_info"]["status"];
					foreach($da["result"]["data"]["result"] as $dada){
						switch($dada["name"]){
							case "总射门":
								$team_score["home_shoot"] = $dada["l"];
								$team_score["guest_shoot"] =  $dada["r"];
							break;
							case "射正球门":
								$team_score["home_target_shoot"] = $dada["l"];
								$team_score["guest_target_shoot"] =  $dada["r"];
							break;
							case "击中门框":
								$team_score["home_woodwork_shoot"] = $dada["l"];
								$team_score["guest_woodwork_shoot"] =  $dada["r"];
							break;
							case "直塞球":
								$team_score["home_straight_plug_ball"] = $dada["l"];
								$team_score["guest_straight_plug_ball"] =  $dada["r"];
							break;
							case "越位":
								$team_score["home_offside"] = $dada["l"];
								$team_score["guest_offside"] =  $dada["r"];
							break;
							case "抢断":
								$team_score["home_steals"] = $dada["l"];
								$team_score["guest_steals"] =  $dada["r"];
							break;
							case "任意球":
								$team_score["home_free_kick"] = $dada["l"];
								$team_score["guest_free_kick"] =  $dada["r"];
							break;
							case "犯规":
								$team_score["home_foul"] = $dada["l"];
								$team_score["guest_foul"] =  $dada["r"];
							break;
							case "角球":
								$team_score["home_corner"] = $dada["l"];
								$team_score["guest_corner"] =  $dada["r"];
							break;
							case "界外球":
								$team_score["home_foul_ball"] = $dada["l"];
								$team_score["guest_foul_ball"] =  $dada["r"];
							break;
							case "超过25码长传":
								$team_score["home_over_25_yard_passes"] = $dada["l"];
								$team_score["guest_over_25_yard_passes"] =  $dada["r"];
							break;
							case "传球成功率":
								$team_score["home_pass_success_rate"] = (int)str_replace("%","",$dada["l"])*100;
								$team_score["guest_pass_success_rate"] = (int)str_replace("%","",$dada["r"])*100;
							break;
							case "传中成功率":
								$team_score["home_pass_center_success_rate"] = (int)str_replace("%","",$dada["l"])*100;
								$team_score["guest_pass_center_success_rate"] = (int)str_replace("%","",$dada["r"])*100;
							break;
							case "抢断成功率":
								$team_score["home_steal_success_rate"] =  (int)str_replace("%","",$dada["l"])*100;
								$team_score["guest_steal_success_rate"] =  (int)str_replace("%","",$dada["r"])*100;
							break;
							case "头球成功率":
								$team_score["home_header_success_rate"] =  (int)str_replace("%","",$dada["l"])*100;
								$team_score["guest_header_success_rate"] =  (int)str_replace("%","",$dada["r"])*100;
							break;
							case "控球率":
								$team_score["home_ball_control_rate"] =  (int)str_replace("%","",$dada["l"])*100;
								$team_score["guest_ball_control_rate"] =  (int)str_replace("%","",$dada["r"])*100;
							break;
							
						}
					}
					unset($save);
					foreach($team_score as $k=>$v){
						if($team_score[$k]!=$re[$k]){
							$save[$k]=$v;
						}
					}
					
					if($save){
						$Teamscore->where("`id`=".$game_id)->save($save);
						$GMS = M("KxdrGames");
						$gms["status"] = $team_score["status"];
						$gms["status_end_time"] = date("Y-m-d H:i:s");
						$GMS->where("`id`=".$re["game_id"])->save($gms);
					}
				}
			}
		}
	}
	public function get_player_event(){		
		Vendor('simple_html_dom');
		$Teamscore = M("KxdrGamesSoccerTeamscore");
		$Playerevent = M("KxdrGamesSoccerPlayerevents");
		$Player = M("KxdrPlayers");
		$Game = M("KxdrGames");
		$Event = M("KxdrGamesSoccerPlayerevents");
		$get_game = $Teamscore->where("DATE_FORMAT(`gaming_time`,'%Y%m%d')=DATE_FORMAT(NOW(),'%Y%m%d')")->getField("`id`,`shuju_url`,`gaming_time`,`private_home_team_id`,`private_guest_team_id`");
		foreach($get_game as $game_id=>$gda){
			if($gda["shuju_url"]){
				preg_match("/\d+/",$gda["shuju_url"],$shuju_id);
				$url = "http://info.sports.sina.com.cn/api/live/opta_lineup.php?format=json&id=o_".$shuju_id[0];
				$da = file_get_html($url);
				$da = (json_decode((string)$da,true));
				print_r($da);
				foreach($da["result"]["data"]["event"] as $event){
					unset($data);
					$data["game_id"]=$game_id;
					$data["match_id"]=str_replace("o_","",$da["result"]["data"]["match"]["id"]);
					$data["home_team_id"]=str_replace("o_","",$da["result"]["data"]["match"]["home_id"]);
					$data["home_name_cn"]=$da["result"]["data"]["match"]["home_name_cn"];
					$data["away_team_id"]=str_replace("o_","",$da["result"]["data"]["match"]["away_id"]);
					$data["away_name_cn"]=$da["result"]["data"]["match"]["away_name_cn"];
					$data["player_id"]=$event["id"];
					$data["player_name"]=$event["l_name_cn"];
					$data["player_name_cn"]=$event["l_name_cn"];
					$data["gaming_time"]=$gda["gaming_time"];
					$data["position_id"]=$event["position_id"];
					$data["position_long_cn"]=$event["position_long_cn"];
					foreach($event["event_info"] as $info){
						$data["order_id"]=$info["order_id"];
						$data["event_code"]=$info["event_code"];
						$data["event_cn"]=$info["event_cn"];
						$data["time_minute"]=$info["time"];
						$Event->add($data);
					}
				}
			}
		}
	}
	public function get_player_score(){
		Vendor('simple_html_dom');
		$Teamscore = M("KxdrGamesSoccerTeamscore");
		$Playerscore = M("KxdrGamesSoccerPlayerscore");
		$Player = M("KxdrPlayers");
		$Game = M("KxdrGames");
		$get_game = $Teamscore->where("DATE_FORMAT(`gaming_time`,'%Y%m%d')=DATE_FORMAT(NOW(),'%Y%m%d')")->getField("`id`,`shuju_url`,`gaming_time`,`private_home_team_id`,`private_guest_team_id`");
		foreach($get_game as $game_id=>$gda){
			if($gda["shuju_url"]){
				preg_match("/\d+/",$gda["shuju_url"],$shuju_id);
				$url = "http://info.sports.sina.com.cn/api/live/opta_player_stats.php?format=json&id=o_".$shuju_id[0];
				$da = file_get_html($url);
				$da = (json_decode((string)$da,true));
				// print_r($da);
				preg_match_all("/\d+/",$da["result"]["data"]["match"]["home_logo_big"],$home_id);
				preg_match_all("/\d+/",$da["result"]["data"]["match"]["away_logo_big"],$away_id);
				$private_ids = $Player->where("`outside_id` IN (".$home_id[0][1].",".$away_id[0][1].") AND `game_category`='football'")->getField("`outside_id`,`id`,`private_league_id`,`league_type`,`league_id`,`league_name`");
				$lid = $Game->where("`name`='".$da["result"]["data"]["match"]["type_name"]."' AND `team_type`='league'")->getField("id");
					if(!$lid){
						unset($league);
						$league["league_type"]='';
						$league["name"]=$da["result"]["data"]["match"]["type_name"];
						$league["short_name"]=$da["result"]["data"]["match"]["type_name"];
						$league["outside_id"]=$da["result"]["data"]["match"]["type_id"];
						$league["is_leaf"]=0;
						$league["is_pub"]=1;
						$league["version"]="sports";
						$league["game_category"]='football';
						$league["fid"]=1;
						$league["team_type"]="league";
						$lid = $Game->add($league);
						echo $Game->getDbError();
					}
				if(!$private_ids[$home_id[0][1]]["id"]){
					unset($player);
					$player["chinese_name"]=$da["result"]["data"]["match"]["home_name_cn"];
					$player["is_team"]=1;
					$player["team_flag"]=$da["result"]["data"]["match"]["home_logo_big"];
					$player["is_pub"]=1;
					$player["outside_id"]=$home_id[0][1];
					$player["version"]="sports";
					$player["game_category"]="football";
					$player["private_league_id"]=$lid;
					$player["league_type"]='';
					$player["league_id"]=$da["result"]["data"]["match"]["type_id"];
					$player["league_name"]=$da["result"]["data"]["match"]["type_name"];
					$private_ids[$home_id[0][1]]["id"] = $Player->add($player);
				}
				if(!$private_ids[$away_id[0][1]]["id"]){
					unset($player);
					$player["chinese_name"]=$da["result"]["data"]["match"]["away_name_cn"];
					$player["is_team"]=1;
					$player["team_flag"]=$da["result"]["data"]["match"]["away_logo_big"];
					$player["is_pub"]=1;
					$player["outside_id"]=$away_id[0][1];
					$player["version"]="sports";
					$player["game_category"]="football";
					$player["private_league_id"]=$lid;
					$player["league_type"]='';
					$player["league_id"]=$da["result"]["data"]["match"]["type_id"];
					$player["league_name"]=$da["result"]["data"]["match"]["type_name"];
					$private_ids[$away_id[0][1]]["id"] = $Player->add($player);
				}
				foreach($da["result"]["data"]["stats"]["home"] as $re){
					$this->save_player_score($gda,$da["result"]["data"]["match"]["home_name_cn"],$da["result"]["data"]["match"]["type_name"],$re,$private_ids,$home_id,$game_id,1);
				}
				foreach($da["result"]["data"]["stats"]["away"] as $re){
					$this->save_player_score($gda,$da["result"]["data"]["match"]["away_name_cn"],$da["result"]["data"]["match"]["type_name"],$re,$private_ids,$away_id,$game_id,0);
				}
			}
		}
	}
	private function save_player_score($gda,$team_name,$lname,$re,$private_ids,$home_id,$game_id,$ishome){
		$Player = M("KxdrPlayers");
		$player_id = $Player->where("`player_id`=".$re["player_id"]." AND `team_id`=".$re["team_id"]." AND `game_category`='football'")->getField("`id`");

		if(!$player_id){
			$player["chinese_name"]=$re["player_name_cn"];
			$player["foreign_name"]=$re["player_name"];
			$player["private_team_id"]=$private_ids[$home_id[0][1]]["id"];
			$player["team_id"]=$re["team_id"];
			$player["player_id"]=$re["player_id"];
			$player["outside_id"]=$re["player_id"];
			$player["private_league_id"]=$private_ids[$home_id[0][1]]["private_league_id"];
			$player["league_type"]=$private_ids[$home_id[0][1]]["league_type"];
			$player["league_id"]=$private_ids[$home_id[0][1]]["league_id"];
			$player["league_join"]=$re["league_id"]; //加入联赛的时间
			$player["league_name"]=$private_ids[$home_id[0][1]]["league_name"];
			$player["is_pub"]=1;
			$player["game_category"]="football";
			$player["version"]='sports';
			$player_id = $Player->add($player);
		}
		echo $player_id;
		$data["game_id"]=$game_id;
		$data["player_id"]=$re["player_id"];
		$data["private_player_id"]=$player_id;
		$data["private_team_id"]=$private_ids[$home_id[0][1]]["id"];
		$data["player_name"]=$re["player_name"];
		$data["player_name_cn"]=$re["player_name_cn"];
		$data["team"]=$team_name;
		$data["team_id"]=$re["team_id"];
		$data["outside_id"]=$re["player_id"];
		$data["match_id"]=$re["match_id"];
		$data["private_league_id"]=$private_ids[$home_id[0][1]]["private_league_id"];
		$data["league_id"]=$private_ids[$home_id[0][1]]["league_id"];
		$data["league_name"]=$lname;
		$data["gaming_time"]=$gda["gaming_time"];
		$data["position_id"]=$re["position_id"];
		$data["shirt_number"]=$re["shirt_number"];
		$data["status"]=$re["status"];
		$data["ishome"]=$ishome;
		$data["starter"]=$re["status"]=='z'?true:false;
		$data["minutes"]=$re["mins_played"]; //出场时间
		$data["shoot"]=$re["total_scoring_att"]; //射门次数
		$data["target_shoot"]=$re["ontarget_scoring_att"]; //射正次数
		$data["goals"]=$re["goals"]; //进球数
		$data["goal_assist"]=$re["goal_assist"]; //进球助攻
		$data["total_att_assist"]=$re["total_att_assist"]; //总进攻助攻
		$data["total_contest"]=$re["total_contest"]; //争抢
		$data["won_contest"]=$re["won_contest"]; //争抢成功
		$data["fouls"]=$re["fouls"]; //犯规
		$data["fouled"]=$re["was_fouled"]; //被犯规
		$data["total_clearance"]=$re["total_clearance"]; //解围
		$data["rescue"]=$re["total_clearance"];  //解围
		$data["total_tackle"]=$re["total_tackle"]; //铲球
		$data["mins_played"]=$re["mins_played"]; //出场时间
		$data["scoring_persent"]=$re["scoring_persent"]; //得分率
		$data["player_status"]=$re["status"]; //是否替补
		$data["player_status_cn"]=$re["status_cn"];//是否替补
		$data["position_cn"]=$re["position_cn"];//位置
		$data["position_long_cn"]=$re["position_long_cn"];//位置
		$data["total_pass"]=$re["total_pass"]; //总传球
		$data["accurate_pass"]=$re["accurate_pass"];//准确传球
		$data["won_tackle"]=$re["won_tackle"]; //铲球成功
		$data["dribble_pass"]= $re["total_pass"]; //总传球
		$data["saves"]=$re["saves"]; //扑救
		$data["goalkeeper_saves"]=$re["saves"]; //扑救
		// $data["threat_ball"]= //威胁球
		// $data["red_card"]=
		// $data["yellow_card"]=
		// $data["add_time"]=
		// $data["edit_time"]=
		// //以下为添加球员得分数据
		$PLRSC = M("KxdrGamesSoccerPlayerscore");
		$sid = $PLRSC->where("`match_id`=".$data["match_id"]." AND `player_id`=".$data["player_id"])->getField("id");
		if(!$sid){
			$data["add_time"]=date("Y-m-d H:i:s");
			$data["edit_time"]=date("Y-m-d H:i:s");
			$PLRSC->add($data);
		}else{
			$data["edit_time"]=date("Y-m-d H:i:s");
			$PLRSC->where("`id`=".$sid)->save($data);
		}
		echo $PLRSC->getDbError();
	}
	private function GrabImage($url,$filename="") {
   if($url==""):return false;endif;
   if($filename=="") {
     $ext=strrchr($url,".");
     if($ext!=".gif" && $ext!=".jpg"):return false;endif;
     $filename=date("dMYHis").$ext;
   }
   ob_start();
   readfile($url);
   $img = ob_get_contents();
   ob_end_clean();
   $size = strlen($img);
   $fp2=@fopen($filename, "a");
   fwrite($fp2,$img);
   fclose($fp2);
   return $filename;
}
	public function index(){
		

		set_time_limit(600);
		// 5秒刷新：http://data.sports.sina.com.cn/live/today.js?0.857032626401633
		// score_live_stats({ms:[{id:1171683,ln:'世俱杯',st:'上22',img:'now1.GIF',n1:'广岛三箭',n2:'奥克兰城',s1:'1-0',s2:'-',r1:'',r2:'',url:''},{id:1158554,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158553,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158542,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158541,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158530,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158529,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158518,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158493,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158494,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158505,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158506,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158517,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158643,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158614,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158613,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158602,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158601,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158590,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158589,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158578,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158577,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158566,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158565,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''},{id:1158644,st:'未赛',img:'',n:'',s1:'-',s2:'-',r1:'',r2:'',url:''}]});
		$url = "http://platform.sina.com.cn/sports_other/livecast_dateschedule?app_key=3633771828&date=".date("Y-m-d",time()+3600*24); //比赛日程最多支持半年
		// 开场以后才可获得：
		// $url = "http://info.sports.sina.com.cn/api/live/opta_statistic.php?format=json&id=o_832692";//球队单场数据
		// $url = "http://info.sports.sina.com.cn/api/live/opta_player_stats.php?format=json&id=o_837820";//球员单场数据
		// $url = "http://info.sports.sina.com.cn/api/live/opta_lineup.php?format=json&id=o_837820";//球队队形、球员红黄牌数据
		
		Vendor('simple_html_dom');
		$html = file_get_html($url);
		$html = (json_decode((string)$html,true));
		$Teamscore = M("KxdrGamesSoccerTeamscore");
		$Game = M("KxdrGames");
		$Player = M("KxdrPlayers");
		foreach($html["result"]["data"] as $gk=>$game){
			// echo $game["id"];
			// echo $game["Team1Id"];  //NBA id格式为：nba_12
			// echo $game["Team2Id"];
			// echo $game["Discipline"]; //英文比赛类别  basketball football
			// echo $game["MatchDate"]." ".$game["MatchTime"];
			// echo $game["Team1"];
			// echo $game["Team2"];
			// echo $game["Flag1"];
			// echo $game["Flag2"];
			// echo $game["Title"];//比赛名称
			// echo $game["type"]; //中文比赛类别
			// echo $game["ShortTitle"]; //联赛缩写
			// echo $game["LeagueType_cn"];//联赛名称
			// echo $game["LeagueType"]; //联赛ID，足球为数字ID，NBA是nba，欧联杯11，冠军杯10，围棋11_c_1,网球tennis_0
			// echo $game["MatchType"]; //比赛类别ID，足球20，NBA24，CBA23，围棋35，
			// echo $game["LiveStatus"]; //0为未赛，2为完赛  status重复字段
			// echo $game["shuju_url"];   //读取id作为详细数据json标识 preg_match("/\d+/",$game["shuju_url"],$sj_id);
			// echo $game["live_url"];
			// echo $game["NewsUrl"];
			// echo $game["VideoUrl"];
			// echo $game["ImgUrl"];
			// echo $game["TV"]; //中文电视台名称
			// echo $game["Television"];//英文电视台名
			// echo $game["popup_url"];//老版即时数据 提取ID作为匹配
		   if($game["Team1Id"]){
			$game["Team1Id"] = preg_replace("/[A-Za-z_]+/","",$game["Team1Id"]);
			$game["Team2Id"] = preg_replace("/[A-Za-z_]+/","",$game["Team2Id"]);
			$game["LeagueType_cn"] = $game["LeagueType_cn"]?$game["LeagueType_cn"]:($game["ShortTitle"]?$game["ShortTitle"]:"其他");
			preg_match("/\d+/",$game["shuju_url"],$outside_id);
			$lid = $Game->where("`league_type`='".$game["LeagueType"]."' AND `team_type`='league'")->getField("id");
				if(!$lid){
					unset($league);
					$league["league_type"]=$game["LeagueType"];
					$league["name"]=$game["LeagueType_cn"];
					$league["short_name"]=$game["ShortTitle"];
					$league["outside_id"]=0;
					$league["is_leaf"]=0;
					$league["is_pub"]=1;
					$league["version"]="sports";
					$league["game_category"]=$game["Discipline"];
					switch($game["Discipline"]){
						case "football":
						$league["fid"]=1;
						break;
						case "basketball":
						$league["fid"]=2;
						break;
						default:
						$league["fid"]=3;
						break;
					}
					$league["team_type"]="league";
					$lid = $Game->add($league);
					echo $Game->getDbError();
				}
				
				$home_player = current($Player->where("`outside_id`=".$game["Team1Id"]." AND `league_type`='".$game["LeagueType"]."'")->getField("id,id,team_flag"));
				$home_player_id = $home_player["id"];
				$guest_player = current($Player->where("`outside_id`=".$game["Team2Id"]." AND `league_type`='".$game["LeagueType"]."'")->getField("id,id,team_flag"));
				$guest_player_id = $guest_player["id"];
				
				//生成比赛banner
				$platform="football_playground.jpg";
				if($game["Discipline"]=="basketball"){$platform="basketball_playground.jpg";}
				unset($pic1);
				unset($hpic);
				$hpic = $this->GrabImage(str_replace("35/","85/",$game["Flag1"]),"/data/home/website24/home_flag.jpg") ;
				if(!$home_player_id){
					$pic1 = $this->upload_img("/data/home/website24/home_flag.jpg"); //队标上传到图片空间
				}else{
					$pic1=$home_player["team_flag"];
				}
				print_r($pic1);
				$game["Flag1"] = $pic1["url"]?$pic1["url"]:$game["Flag1"];
				sleep(1);
				unset($pic2);
				unset($gpic);
				$gpic = $this->GrabImage(str_replace("35/","85/",$game["Flag2"]),"/data/home/website24/guest_flag.jpg") ;
				if(!$guest_player_id){
					$pic2 = $this->upload_img("/data/home/website24/guest_flag.jpg"); //队标上传到图片空间
				}else{
					$pic2 = $guest_player["team_flag"];
				}
				print_r($pic2);
				$game["Flag2"] = $pic2["url"]?$pic2["url"]:$game["Flag2"];
				sleep(1);			
				
				$banner = $this->img($hpic,$gpic,$game["LeagueType_cn"],$game["Team1"]." VS ".$game["Team2"],$platform);
				print_r($banner);
				$game["banner"] = $banner["url"];
				sleep(1);
				// print_r($pic1);
				// print_r($pic2);
				// print_r($banner);
				// die();
				unset($data);
				$data["fid"]=$lid;
				$data["name"]=$game["Title"];
				$data["league_type"]=$game["LeagueType"];
				$data["outside_id"]=0;
				$data["match_id"]=$game["id"];
				$data["is_leaf"]=1;
				$data["is_pub"]=1;
				$data["start_time"]=$game["MatchDate"]." ".$game["MatchTime"];;
				$data["version"]="sports";
				$data["game_category"]=$game["Discipline"];
				$data["team_type"]="match";
				$data["pic_url"]=$banner["url"]; //比赛banner
				$data["base_pic_url"]=$str; //比赛banner的基础路径
				$data["shilu_url"]=$game["shilu_url"]; //文字直播实录
				$data["live_url"]=$game["live_url"]; //图文直播
				$data["news_url"]=$game["NewsUrl"]; //相关新闻
				$data["video_url"]=$game["VideoUrl"]; //视频新闻
				$data["img_url"]=$game["ImgUrl"]; //图片新闻
				$data["tv"]=$game["TV"]; //中文电视台名称
				$data["television"]=$game["Television"]; //英文电视台名称
			
				$game_id = $Game->where("match_id=".$data["match_id"]." AND `league_type`='".$game["LeagueType"]."'")->getField("id"); 
				if(!$game_id){
					$game_id = $Game->add($data);
				}
				echo $Game->getDbError();
				// echo $Game->_sql();
				// $home_player_id = $Player->where("`outside_id`=".$game["Team1Id"]." AND `league_type`='".$game["LeagueType"]."'")->getField("id");
				// $guest_player_id = $Player->where("`outside_id`=".$game["Team2Id"]." AND `league_type`='".$game["LeagueType"]."'")->getField("id");
				if(!$home_player_id){
					unset($player);
					$player["chinese_name"]=$game["Team1"];
					$player["is_team"]=1;
					$player["team_flag"]=$game["Flag1"];
					$player["is_pub"]=1;
					$player["outside_id"]=$game["Team1Id"];
					$player["version"]="sports";
					$player["game_category"]=$game["Discipline"];
					$player["private_league_id"]=$lid;
					$player["league_type"]=$game["LeagueType"];
					$player["league_id"]=0;
					$player["league_name"]=$game["LeagueType_cn"];
					$home_player_id = $Player->add($player);
				echo $Player->getDbError();
				}
				if(!$guest_player_id){
					unset($player);
					$player["chinese_name"]=$game["Team2"];
					$player["is_team"]=1;
					$player["team_flag"]=$game["Flag2"];
					$player["is_pub"]=1;
					$player["outside_id"]=$game["Team2Id"];
					$player["version"]="sports";
					$player["game_category"]=$game["Discipline"];
					$player["private_league_id"]=$lid;
					$player["league_type"]=$game["LeagueType"];
					$player["league_id"]=0;
					$player["league_name"]=$game["LeagueType_cn"];
					$guest_player_id = $Player->add($player);
				echo $Player->getDbError();
				}
				
				if($game["Discipline"]=="football"){
					$tmp["game_id"]=$game_id;
					$tmp["shuju_url"]=$game["shuju_url"];
					$tmp["private_home_team_id"]=$home_player_id;
					$tmp["private_guest_team_id"]=$guest_player_id; 
					$tmp["outside_id"]=$outside_id[0];
					$tmp["match_id"]=$game["id"];
					$tmp["private_league_id"]=$lid;
					$tmp["league_type"]=$game["LeagueType"];
					$tmp["league_id"]=0;
					$tmp["league_name"]=$game["LeagueType_cn"];
					$tmp["home_team"]=$game["Team1"];
					$tmp["home_team_id"]=$game["Team1Id"];
					$tmp["guest_team"]=$game["Team2"];
					$tmp["guest_team_id"]=$game["Team2Id"];
					$tmp["gaming_time"]=$game["MatchDate"]." ".$game["MatchTime"];
					$tmp["status"]=17;
					$tmp["home_team_url"]=(string)$zhuangtai_a[0]->href;
					$tmp["guest_team_url"]=(string)$zhuangtai_a[2]->href;
					// $tmp["home_team_rank"]
					$tmp["home_team_score"]=$game["Score1"];
					$tmp["guest_team_score"]=$game["Score2"];
					$tmp["home_flag"]=$game["Flag1"];
					$tmp["guest_flag"]=$game["Flag2"];
					$tmp["home_team_redcard"]=0;
					$tmp["guest_team_redcard"]=0;
					$tmp["home_team_yellowcard"]=0;
					$tmp["guest_team_yellowcard"]=0; 
					$tmp["home_team_halfscore"]=0;
					$tmp["guest_team_halfscore"]=0;
					$tmp["status"]=$game["status"];
					$tmp["add_time"]=date("Y-m-d H:i:s");
					$Teamscore->add($tmp);
					echo $Teamscore->getDbError();
				}
			$html["result"]["data"][$gk]=$game;
		   }
		}
		$this->send_data_to_tae($html);
	}

}